<template>
  <div class="my-questions-page">
    <div class="page-container">
      <!-- 页面头部 -->
      <div class="page-header">
        <div class="header-content">
          <div class="header-left">
            <h1 class="page-title">
              <i class="fas fa-list-alt"></i>
              我的试题
            </h1>
            <p class="page-subtitle">管理和创建您的编程题目</p>
            <div class="local-storage-notice">
              <i class="fas fa-info-circle"></i>
              您的题目数据安全保存在本地浏览器中
            </div>
            

          </div>
                  <div class="header-actions">
          <button @click="refreshQuestions" class="refresh-btn" :disabled="loading" title="刷新题目列表，重新从本地存储加载数据">
            <i class="fas fa-sync-alt" :class="{ 'fa-spin': loading }"></i>
            刷新
          </button>
          <button @click="createNewQuestion" class="create-btn" title="创建新的编程题目">
            <i class="fas fa-plus"></i>
            创建新题目
          </button>

        </div>
        </div>
      </div>

      <!-- 批量操作区域 -->
      <div v-if="hasSelectedQuestions" class="bulk-actions-section">
        <div class="bulk-actions-content">
          <div class="selection-info">
            <i class="fas fa-check-square"></i>
            已选择 {{ selectedQuestions.length }} 个题目
          </div>
          <div class="bulk-buttons">
            <button @click="bulkDelete" class="bulk-btn delete" title="删除所有选中的题目，此操作不可撤销">
              <i class="fas fa-trash"></i>
              批量删除
            </button>
            <button @click="bulkChangeStatus(1)" class="bulk-btn public" title="将选中的题目设为公开状态">
              <i class="fas fa-globe"></i>
              设为公开
            </button>
            <button @click="bulkChangeStatus(0)" class="bulk-btn private" title="将选中的题目设为私有状态">
              <i class="fas fa-lock"></i>
              设为私有
            </button>
            <button @click="clearSelection" class="bulk-btn clear" title="取消选择所有题目">
              <i class="fas fa-times"></i>
              取消选择
            </button>
          </div>
        </div>
      </div>

      <!-- 统计信息 -->
      <div class="stats-section">
        <div class="stat-card">
          <div class="stat-icon total">
            <i class="fas fa-tasks"></i>
          </div>
          <div class="stat-info">
            <h3>{{ questionStats.total }}</h3>
            <p>总题目数</p>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon public">
            <i class="fas fa-globe"></i>
          </div>
          <div class="stat-info">
            <h3>{{ questionStats.public }}</h3>
            <p>公开题目</p>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon private">
            <i class="fas fa-lock"></i>
          </div>
          <div class="stat-info">
            <h3>{{ questionStats.private }}</h3>
            <p>私有题目</p>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon submissions">
            <i class="fas fa-chart-line"></i>
          </div>
          <div class="stat-info">
            <h3>{{ questionStats.totalSubmissions }}</h3>
            <p>总提交数</p>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon easy">
            <i class="fas fa-star"></i>
          </div>
          <div class="stat-info">
            <h3>{{ questionStats.averageDifficulty }}</h3>
            <p>平均难度</p>
          </div>
        </div>
        <div class="stat-card">
          <div class="stat-icon popular">
            <i class="fas fa-fire"></i>
          </div>
          <div class="stat-info">
            <h3>{{ questionStats.mostPopularType }}</h3>
            <p>最热类型</p>
          </div>
        </div>
      </div>

      <!-- 搜索和筛选 -->
      <div class="filter-section">
        <div class="search-row">
          <div class="search-box">
            <i class="fas fa-search"></i>
            <input 
              v-model="searchForm.keyword" 
              placeholder="搜索题目名称..." 
              @keyup.enter="searchQuestions"
            >
          </div>
          <button @click="searchQuestions" class="search-btn" title="根据输入的关键词和筛选条件搜索题目">
            <i class="fas fa-search"></i>
            搜索
          </button>
          <button @click="resetSearch" class="reset-btn" title="清空搜索条件，显示所有题目">
            <i class="fas fa-refresh"></i>
            重置
          </button>
        </div>
        
        <div class="filter-controls">
          <select v-model="searchForm.difficulty" @change="searchQuestions">
            <option value="">所有难度</option>
            <option value="1">难度 1</option>
            <option value="2">难度 2</option>
            <option value="3">难度 3</option>
            <option value="4">难度 4</option>
            <option value="5">难度 5</option>
            <option value="6">难度 6</option>
          </select>
          <select v-model="searchForm.sortBy" @change="searchQuestions">
            <option value="">默认排序</option>
            <option value="createTime">创建时间</option>
            <option value="difficulty">难度等级</option>
            <option value="submissionQuantity">提交数量</option>
            <option value="byQuantity">通过数量</option>
          </select>
        </div>

        <!-- 快速筛选和全选 -->
        <div class="quick-actions">
          <div class="select-all">
            <input 
              type="checkbox" 
              id="selectAll" 
              v-model="selectAllState" 
              @change="toggleSelectAll"
              class="select-all-checkbox"
            >
            <label for="selectAll">全选当前页</label>
          </div>
          <div class="quick-filters">
            <span class="filter-label">快速筛选：</span>
            <button @click="quickFilter('recent')" class="quick-filter-btn" title="显示最近7天创建的题目">
              <i class="fas fa-clock"></i>
              最近创建
            </button>
          </div>
        </div>
      </div>

      <!-- 题目列表 -->
      <div class="questions-section">
        <div v-if="loading" class="loading-state">
          <i class="fas fa-spinner fa-spin"></i>
          <p>正在加载题目...</p>
        </div>

        <!-- 调试信息已移除 -->

        <div v-else-if="questions.length === 0" class="empty-state">
          <div class="empty-icon">
            <i class="fas fa-inbox"></i>
          </div>
          <h3>{{ emptyStateTitle }}</h3>
          <p>{{ emptyStateMessage }}</p>
          
          <!-- 如果是刚创建的题目，显示额外的提示 -->
          <div v-if="emptyStateTitle === '题目创建成功！'" class="creation-notice">
            <p><i class="fas fa-info-circle"></i> 如果题目没有显示，可能是以下原因：</p>
            <ul>
              <li>数据正在同步中，请稍后点击"刷新"按钮</li>
              <li>创建后可能需要一些时间才能显示</li>
            </ul>
          </div>
          
          <div class="empty-actions">
            <button @click="refreshQuestions" class="empty-refresh-btn">
              <i class="fas fa-sync-alt"></i>
              刷新数据
            </button>
            <button @click="createNewQuestion" class="empty-create-btn">
              <i class="fas fa-plus"></i>
              立即创建
            </button>
          </div>
        </div>

        <div v-else class="questions-grid">
          <div 
            v-for="question in questions" 
            :key="question.id" 
            class="question-card"
            :class="{ 'selected': question.selected }"
          >
            <div class="question-header">
              <div class="question-select">
                <input 
                  type="checkbox" 
                  :id="'question-' + question.id" 
                  v-model="question.selected" 
                  @click.stop
                  class="question-checkbox"
                >
              </div>
              <div class="question-title">{{ question.questionName }}</div>
              <div class="question-actions">
                <button @click.stop="viewQuestionDetail(question.id)" class="action-btn view" title="查看详情">
                  <i class="fas fa-eye"></i>
                  <span>查看</span>
                </button>
                <button @click.stop="editQuestion(question.id)" class="action-btn edit" title="编辑题目">
                  <i class="fas fa-edit"></i>
                  <span>编辑</span>
                </button>
                <button @click.stop="shareQuestion(question)" class="action-btn share" title="共享题目">
                  <i class="fas fa-share-alt"></i>
                  <span>共享</span>
                </button>
                <button @click.stop="deleteQuestion(question.id)" class="action-btn delete" title="删除题目">
                  <i class="fas fa-trash"></i>
                  <span>删除</span>
                </button>
              </div>
            </div>
            
            <div class="question-meta">
              <span class="difficulty-badge" :class="getDifficultyClass(question.difficulty)">
                {{ getDifficultyText(question.difficulty) }}
              </span>
              <span class="type-badge">
                {{ getTypeText(question.questionType) }}
              </span>
              <span class="status-badge" :class="question.isPublic ? 'public' : 'private'">
                {{ question.isPublic ? '公开' : '私有' }}
              </span>
            </div>

            <div class="question-description">
              {{ truncateText(question.questionDescribe, 100) }}
            </div>

            <div class="question-stats">
              <div class="stat-item">
                <i class="fas fa-eye"></i>
                <span>{{ question.submissionQuantity || 0 }} 次提交</span>
              </div>
              <div class="stat-item">
                <i class="fas fa-check-circle"></i>
                <span>{{ question.byQuantity || 0 }} 次通过</span>
              </div>
              <div class="stat-item">
                <i class="fas fa-clock"></i>
                <span>{{ question.timeLimit }}ms</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div v-if="questions.length > 0" class="pagination">
          <button 
            @click="changePage(currentPage - 1)" 
            :disabled="currentPage <= 1"
            class="page-btn"
          >
            <i class="fas fa-chevron-left"></i>
          </button>
          
          <span class="page-info">
            第 {{ currentPage }} 页，共 {{ totalPages }} 页
          </span>
          
          <button 
            @click="changePage(currentPage + 1)" 
            :disabled="currentPage >= totalPages"
            class="page-btn"
          >
            <i class="fas fa-chevron-right"></i>
          </button>
        </div>
      </div>
    </div>

    <!-- 共享弹窗 -->
    <div v-if="showShareModal" class="share-modal-overlay" @click="closeShareModal">
      <div class="share-modal" @click.stop>
        <div class="share-modal-header">
          <h3>共享试题</h3>
          <button @click="closeShareModal" class="close-btn">
            <i class="fas fa-times"></i>
          </button>
        </div>
        
        <div class="share-modal-body">
          <div class="question-info">
            <h4>{{ shareTargetQuestion?.questionName }}</h4>
            <p>即将共享给其他用户</p>
          </div>
          
          <div class="share-form">
            <label for="targetUserId">目标用户ID：</label>
            <input 
              type="text" 
              id="targetUserId" 
              v-model="shareForm.targetUserId" 
              placeholder="请输入目标用户的数字ID（如：1951561204828868608）"
              @keyup.enter="confirmShare"
              ref="targetUserIdInput"
            >
            <div v-if="shareForm.error" class="error-message">
              {{ shareForm.error }}
            </div>
          </div>
        </div>
        
        <div class="share-modal-footer">
          <button @click="closeShareModal" class="cancel-btn">取消</button>
          <button @click="confirmShare" class="confirm-btn" :disabled="shareForm.loading">
            <i v-if="shareForm.loading" class="fas fa-spinner fa-spin"></i>
            <i v-else class="fas fa-share-alt"></i>
            {{ shareForm.loading ? '共享中...' : '确认共享' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getUserCreatedQuestions, deleteTestQuestion, getTestQuestionById, shareQuizToUser } from '@/api/testQuestion'
import { getMyCreatQuestion } from '@/api/homework'
import logger from '../utils/logger.js'
// import { getMyQuestions, deleteQuestion as deleteQuestionAPI, updateQuestion } from '@/api/question'
// 现在使用本地存储，但刷新时会调用后端API

export default {
  name: 'MyQuestions',
  data() {
    return {
      loading: false,
      questions: [],
      questionStats: {
        total: 0,
        public: 0,
        private: 0,
        totalSubmissions: 0,
        averageDifficulty: '-',
        mostPopularType: '-'
      },
      searchForm: {
        keyword: '',
        difficulty: '',
        sortBy: ''
      },
      selectAllState: false,
      currentPage: 1,
      pageSize: 12,
      totalPages: 1,
      totalCount: 0,
      // 动态空状态消息
      emptyStateTitle: '还没有创建任何题目',
      emptyStateMessage: '点击上方的"创建新题目"按钮开始创建您的第一个编程题目',
      // 共享相关数据
      showShareModal: false,
      shareTargetQuestion: null,
      shareForm: {
        targetUserId: '',
        loading: false,
        error: ''
      }
    }
  },

  computed: {
    // 已选择的题目
    selectedQuestions() {
      return this.questions.filter(q => q.selected);
    },
    
    // 是否有选择的题目
    hasSelectedQuestions() {
      return this.selectedQuestions.length > 0;
    }
  },

  methods: {
    // 创建新题目
    createNewQuestion() {
      logger.log('🎯 [MyQuestions] 跳转到创建题目页面');
      this.$router.push('/question/create');
    },

    // 手动刷新 - 只使用新的homework API接口获取数据
    async refreshQuestions() {
      logger.log('🔄 [MyQuestions] 手动刷新题目列表 - 使用新的homework API接口');
      
      if (this.loading) return;
      this.loading = true;
      
      try {
        // 重置到第一页
        this.currentPage = 1;
        
        // 构建API查询参数
        const apiParams = {
          page: this.currentPage  // 使用page参数，不传size参数（使用后端默认10条）
        };
        
        // 添加搜索条件（如果有的话）
        if (this.searchForm.keyword) {
          apiParams.keyword = this.searchForm.keyword;
        }
        if (this.searchForm.difficulty) {
          apiParams.difficulty = parseInt(this.searchForm.difficulty);
        }
        
        logger.log('📡 [MyQuestions] 调用homework API接口获取我创建的题目列表...');
        logger.log('🌐 [MyQuestions] 接口地址: /goc/homework/myCreatQuestion');
        logger.log('📋 [MyQuestions] API参数:', apiParams);
        
        // 使用homework API接口获取我创建的题目
        const response = await getMyCreatQuestion(apiParams);
        
        logger.log('✅ [MyQuestions] 新API接口调用成功:', response);
        
        if (response && response.code === 0 && response.data && response.data.records) {
          const apiData = response.data;
          
          // 更新题目列表数据
          this.questions = apiData.records.map(question => ({
            ...question,
            selected: false // 添加选择状态
          }));
          
          // 更新分页信息
          this.totalCount = apiData.total || 0;
          this.totalPages = apiData.pages || Math.ceil(this.totalCount / 10); // 后端默认每页10条
          
          // 更新统计信息
          this.updateStats();
          
          // 可选：同步到本地存储
          try {
            const { default: localQuestionStorage } = await import('@/utils/localStorage');
            apiData.records.forEach(question => {
              localQuestionStorage.saveQuestion(question);
            });
            logger.log('💾 [MyQuestions] 数据已同步到本地存储');
          } catch (syncError) {
            logger.warn('⚠️ [MyQuestions] 同步到本地存储失败:', syncError);
          }
          
          logger.log('🎉 [MyQuestions] 刷新完成:', this.questions.length, '条题目');
          
          logger.log(`✅ [MyQuestions] 刷新成功！获取到 ${this.questions.length} 条题目`);
          
        } else {
          logger.warn('⚠️ [MyQuestions] API响应格式异常:', response);
          throw new Error('API响应数据格式不正确');
        }
        
      } catch (error) {
        logger.error('❌ [MyQuestions] 刷新题目列表失败:', error);
        
        let errorMessage = '刷新失败，请重试';
        if (error.response) {
          errorMessage = `刷新失败 (${error.response.status}): ${error.response.data?.message || '服务器错误'}`;
        } else if (error.message) {
          errorMessage = `刷新失败: ${error.message}`;
        }
        
        if (this.$message && this.$message.error) {
          this.$message.error(errorMessage);
        }
        
        // 不再回退到本地存储，只使用新的API接口
        logger.log('❌ [MyQuestions] 新API接口调用失败，请检查网络连接或联系管理员');
        
      } finally {
        this.loading = false;
      }
    },

    // 搜索题目
    async searchQuestions() {
      this.currentPage = 1;
      await this.loadQuestions();
    },

    // 加载题目列表
    async loadQuestions() {
      if (this.loading) return;
      
      this.loading = true;
      
      try {
        logger.log('📋 [MyQuestions] 加载题目列表...');
        
        // 获取当前用户ID
        const currentUserId = this.getCurrentUserId();
        logger.log('👤 [MyQuestions] 当前用户ID:', currentUserId);
        
        // 优先尝试从后端API获取数据
        logger.log('🌐 [MyQuestions] 优先从后端API获取题目数据...');
        try {
          // 构建API查询参数
          const apiParams = {
            page: this.currentPage  // 使用page参数，不传size参数（使用后端默认10条）
          };
          
          // 添加搜索条件（如果有的话）
          if (this.searchForm.keyword) {
            apiParams.keyword = this.searchForm.keyword;
          }
          if (this.searchForm.difficulty) {
            apiParams.difficulty = parseInt(this.searchForm.difficulty);
          }
          
          logger.log('📡 [MyQuestions] 调用homework API获取我创建的题目列表...');
          logger.log('📋 [MyQuestions] API参数:', apiParams);
          
          // 调用homework API接口获取我创建的题目
          const response = await getMyCreatQuestion(apiParams);
          
          logger.log('✅ [MyQuestions] 后端API调用成功:', response);
          
          // 检查API响应格式
          if (response && response.code === 0 && response.data) {
            const apiData = response.data;
            
            // 更新题目列表数据
            this.questions = apiData.records.map(question => ({
              ...question,
              selected: false // 添加选择状态
            }));
            
            // 更新分页信息
            this.totalCount = apiData.total || 0;
            this.totalPages = apiData.pages || Math.ceil(this.totalCount / 10); // 后端默认每页10条
            
            // 更新统计信息
            this.updateStats();
            
            logger.log('🎉 [MyQuestions] 从后端API加载题目成功:', this.questions.length, '条题目');
            
            // 可选：同步到本地存储作为备份
            try {
              const { default: localQuestionStorage } = await import('@/utils/localStorage');
              apiData.records.forEach(question => {
                localQuestionStorage.saveQuestion(question);
              });
              logger.log('💾 [MyQuestions] 数据已同步到本地存储作为备份');
            } catch (syncError) {
              logger.warn('⚠️ [MyQuestions] 同步到本地存储失败:', syncError);
            }
            
            return; // 成功获取后端数据，直接返回
          } else {
            logger.error('❌ [MyQuestions] API响应格式检查失败');
            logger.error('🔍 [MyQuestions] 实际响应结构:', {
              hasResponse: !!response,
              responseCode: response?.code,
              hasData: !!response?.data,
              dataStructure: response?.data ? Object.keys(response.data) : null
            });
            throw new Error(`后端API响应数据格式不正确: ${JSON.stringify(response)}`);
          }
          
        } catch (apiError) {
          logger.error('❌ [MyQuestions] 后端API获取失败:', apiError);
          logger.log('🔄 [MyQuestions] API失败，回退到本地存储...');
        }
        
        // 如果后端API失败，回退到本地存储
        logger.log('💾 [MyQuestions] 从本地存储加载题目...');
        const { default: localQuestionStorage } = await import('@/utils/localStorage');
        
        const searchParams = {
          ...this.searchForm
        };
        
        // 过滤空值
        Object.keys(searchParams).forEach(key => {
          if (searchParams[key] === '' || searchParams[key] === null || searchParams[key] === undefined) {
            delete searchParams[key];
          }
        });
        
        logger.log('🔍 [MyQuestions] 本地搜索参数:', searchParams);
        
        // 从本地存储获取分页数据
        const localResult = localQuestionStorage.getPagedQuestions(
          searchParams, 
          this.currentPage, 
          this.pageSize
        );
        
        logger.log('📊 [MyQuestions] 本地存储结果:', localResult);
        
        // 设置题目数据
        this.questions = localResult.questions.map(q => ({
          ...q,
          selected: false // 添加选择状态
        }));
        this.totalCount = localResult.total;
        this.totalPages = localResult.totalPages;
        
        // 更新统计信息
        this.updateStats();
        
        logger.log('✅ [MyQuestions] 从本地存储加载题目成功:', this.questions.length);

        // 可选：同时尝试从后端API获取（如果需要同步）
        // this.syncWithBackend(params);
        
      } catch (error) {
        logger.error('❌ [MyQuestions] 加载题目列表失败:', error);
        
        // 显示更详细的错误信息
        let errorMessage = '加载题目失败，请重试';
        if (error.response) {
          errorMessage = `加载失败 (${error.response.status}): ${error.response.data?.message || '服务器错误'}`;
        } else if (error.message) {
          errorMessage = `加载失败: ${error.message}`;
        }
        
        if (this.$message && this.$message.error) {
          this.$message.error(errorMessage);
        } else {
          alert(errorMessage);
        }
        this.questions = [];
      } finally {
        this.loading = false;
      }
    },

    // 更新统计信息
    updateStats() {
      this.questionStats.total = this.questions.length;
      this.questionStats.public = this.questions.filter(q => q.isPublic === 1).length;
      this.questionStats.private = this.questions.filter(q => q.isPublic === 0).length;
      this.questionStats.totalSubmissions = this.questions.reduce((sum, q) => sum + (q.submissionQuantity || 0), 0);
      
      // 计算平均难度
      if (this.questions.length > 0) {
        const totalDifficulty = this.questions.reduce((sum, q) => sum + (q.difficulty || 1), 0);
        const avgDifficulty = (totalDifficulty / this.questions.length).toFixed(1);
        const difficultyTexts = ['', '简单', '中等', '困难', '专家'];
        const difficultyIndex = Math.round(avgDifficulty);
        this.questionStats.averageDifficulty = difficultyTexts[difficultyIndex] || '中等';
      } else {
        this.questionStats.averageDifficulty = '-';
      }
      
      // 找出最热门的题目类型
      if (this.questions.length > 0) {
        const typeCounts = {};
        this.questions.forEach(q => {
          const type = q.questionType || 1;
          typeCounts[type] = (typeCounts[type] || 0) + 1;
        });
        
        const mostPopularTypeId = Object.keys(typeCounts).reduce((a, b) => 
          typeCounts[a] > typeCounts[b] ? a : b
        );
        
        const typeTexts = {
          1: '算法题',
          2: '数据结构',
          3: '动态规划',
          4: '图论',
          5: '字符串',
          6: '数学题',
          7: '数组题'
        };
        
        this.questionStats.mostPopularType = typeTexts[mostPopularTypeId] || '算法题';
      } else {
        this.questionStats.mostPopularType = '-';
      }
    },

    // 切换页面
    changePage(page) {
      if (page < 1 || page > this.totalPages) return;
      this.currentPage = page;
      this.loadQuestions();
    },

    // 查看题目详情
    async viewQuestionDetail(questionId) {
      logger.log('👀 [MyQuestions] 查看题目详情:', questionId);
      
      if (!questionId) {
        logger.error('❌ [MyQuestions] 题目ID不能为空');
        if (this.$message && this.$message.error) {
          this.$message.error('题目ID不能为空');
        }
        return;
      }
      
      try {
        logger.log('📡 [MyQuestions] 调用findById接口获取题目详情...');
        logger.log('🌐 [MyQuestions] 接口地址: /goc/testQuestion/findById');
        logger.log('📋 [MyQuestions] 题目ID:', questionId);
        
        // 调用API获取题目详情
        const response = await getTestQuestionById(questionId);
        
        logger.log('✅ [MyQuestions] 题目详情获取成功:', response);
        
        if (response && response.data) {
          // 处理获取到的题目详情数据
          const questionDetail = response.data;
          logger.log('📄 [MyQuestions] 题目详情数据:', questionDetail);
          
          // 可以在这里处理题目详情，比如显示在弹窗中或跳转到详情页
          // 目前先跳转到问题详情页面
          this.$router.push(`/problem/${questionId}`);
          
          logger.log('✅ [MyQuestions] 题目详情加载成功');
          
        } else {
          throw new Error('API响应数据格式异常');
        }
        
      } catch (error) {
        logger.error('❌ [MyQuestions] 获取题目详情失败:', error);
        
        let errorMessage = '获取题目详情失败，请重试';
        if (error.response) {
          errorMessage = `获取失败 (${error.response.status}): ${error.response.data?.message || '服务器错误'}`;
        } else if (error.message) {
          errorMessage = `获取失败: ${error.message}`;
        }
        
        if (this.$message && this.$message.error) {
          this.$message.error(errorMessage);
        }
        
        // 如果API调用失败，仍然尝试跳转到详情页（使用现有逻辑作为备选）
        logger.log('🔄 [MyQuestions] API失败，使用备选方案跳转到详情页');
        this.$router.push(`/problem/${questionId}`);
      }
    },

    // 编辑题目
    editQuestion(questionId) {
      logger.log('✏️ [MyQuestions] 编辑题目:', questionId);
      this.$router.push(`/question/edit/${questionId}`);
    },

    // 复制题目
    async copyQuestion(question) {
      try {
        logger.log('📋 [MyQuestions] 复制题目:', question.id);
        
        // 创建题目副本数据
        const copyData = {
          ...question,
          questionName: `${question.questionName}（副本）`,
          createUserId: this.getCurrentUserId(),
          isPublic: 0, // 默认设为私有
          submissionQuantity: 0,
          byQuantity: 0
        };
        
        // 删除不需要的字段
        delete copyData.id;
        delete copyData.selected;
        delete copyData.createTime;
        delete copyData.updateTime;
        delete copyData.source;
        
        logger.log('📋 [MyQuestions] 复制数据:', copyData);
        
        // 保存到本地存储
        const { default: localQuestionStorage } = await import('@/utils/localStorage');
        localQuestionStorage.saveQuestion(copyData);
        
        logger.log('✅ [MyQuestions] 题目复制成功');
        
        // 重新加载列表
        await this.loadQuestions();
        
      } catch (error) {
        logger.error('❌ [MyQuestions] 复制题目失败:', error);
        if (this.$message && this.$message.error) {
          this.$message.error('复制题目失败，请重试');
        } else {
          alert('复制题目失败，请重试');
        }
      }
    },

    // 删除题目
    async deleteQuestion(questionId) {
      const confirmed = confirm('确定要删除这个题目吗？此操作不可恢复。');
      if (!confirmed) return;

      try {
        logger.log('🗑️ [MyQuestions] 删除题目:', questionId);
        
        // 优先尝试API删除，失败时使用本地存储
        let deleteResult = null;
        
        try {
          logger.log('🌐 [MyQuestions] 尝试使用API删除题目...');
          const response = await deleteTestQuestion(questionId);
          logger.log('✅ [MyQuestions] API删除响应:', response);
          
          // 检查删除结果
          if (response && response.data && response.data.code === 0) {
            logger.log('✅ [MyQuestions] API删除成功');
            deleteResult = response;
          } else {
            throw new Error(`API删除失败: ${response?.data?.message || '未知错误'}`);
          }
        } catch (apiError) {
          logger.warn('⚠️ [MyQuestions] API删除失败，使用本地存储:', apiError);
          
          // 备用方案：从本地存储删除
          const { default: localQuestionStorage } = await import('@/utils/localStorage');
          deleteResult = localQuestionStorage.deleteQuestion(questionId);
          logger.log('🗑️ [MyQuestions] 本地存储删除结果:', deleteResult);
        }
        
        // 同时从本地存储删除（确保数据同步）
        try {
          const { default: localQuestionStorage } = await import('@/utils/localStorage');
          localQuestionStorage.deleteQuestion(questionId);
          logger.log('💾 [MyQuestions] 已从本地存储同步删除');
        } catch (syncError) {
          logger.warn('⚠️ [MyQuestions] 本地存储同步删除失败:', syncError);
        }
        
        logger.log('✅ [MyQuestions] 题目删除成功');
        
        // 重新加载列表
        await this.loadQuestions();
        
      } catch (error) {
        logger.error('❌ [MyQuestions] 删除题目失败:', error);
        if (this.$message && this.$message.error) {
          this.$message.error('删除题目失败，请重试');
        } else {
          alert('删除题目失败，请重试');
        }
      }
    },

    // 获取难度等级样式类
    getDifficultyClass(difficulty) {
      const classes = {
        1: 'easy',
        2: 'medium', 
        3: 'hard',
        4: 'expert'
      };
      return classes[difficulty] || 'easy';
    },

    // 获取难度等级文字
    getDifficultyText(difficulty) {
      const texts = {
        1: '⭐ 简单',
        2: '⭐⭐ 中等',
        3: '⭐⭐⭐ 困难',
        4: '⭐⭐⭐⭐ 专家'
      };
      return texts[difficulty] || '未知';
    },

    // 获取题目类型文字
    getTypeText(type) {
      const types = {
        1: '算法题',
        2: '数据结构',
        3: '动态规划',
        4: '图论',
        5: '字符串处理',
        6: '数学计算',
        7: '数组操作'
      };
      return types[type] || '其他';
    },

    // 截断文字
    truncateText(text, maxLength) {
      if (!text) return '';
      return text.length > maxLength ? text.substring(0, maxLength) + '...' : text;
    },

    // 处理页面可见性变化
    handleVisibilityChange() {
      if (!document.hidden) {
        logger.log('👁️ [MyQuestions] 页面变为可见，检查是否需要刷新数据');
        // 页面变为可见时总是刷新数据，确保显示最新状态
        if (!this.loading) {
          logger.log('👁️ [MyQuestions] 刷新数据以确保显示最新状态');
          this.loadQuestions();
        } else {
          logger.log('👁️ [MyQuestions] 正在加载中，跳过重新加载');
        }
      }
    },

    // 获取当前用户ID
    getCurrentUserId() {
      try {
        // 首先尝试从JWT令牌中解析用户ID（修复精度丢失问题）
        const token = localStorage.getItem('token');
        if (token) {
          try {
            const tokenParts = token.split('.');
            if (tokenParts.length === 3) {
              // 关键修复：直接解析base64字符串，避免JSON.parse的数字精度丢失
              const payloadBase64 = tokenParts[1];
              const payloadStr = atob(payloadBase64);
              logger.log('🔍 [MyQuestions] JWT payload字符串:', payloadStr);
              
              // 使用正则表达式提取ID，保持字符串格式
              const idMatch = payloadStr.match(/"id":(\d+)/);
              if (idMatch && idMatch[1]) {
                const userId = idMatch[1]; // 保持字符串格式
                logger.log('👤 [MyQuestions] 从JWT令牌获取用户ID (字符串格式):', userId);
                logger.log('👤 [MyQuestions] 用户ID长度:', userId.length, '位');
                return userId;
              }
              
              // 备用方案：如果正则匹配失败，使用JSON.parse但立即转为字符串
              const payload = JSON.parse(payloadStr);
              const userIdNum = payload.claims?.id;
              if (userIdNum) {
                const userId = String(userIdNum);
                logger.warn('⚠️ [MyQuestions] 使用备用方案获取用户ID，可能有精度丢失:', userId);
                return userId;
              }
            }
          } catch (tokenError) {
            logger.warn('⚠️ [MyQuestions] JWT令牌解析失败:', tokenError);
          }
        }
        
        // 备选方案：从localStorage获取用户信息
        const userInfoStr = localStorage.getItem('userInfo');
        if (userInfoStr) {
          const userInfo = JSON.parse(userInfoStr);
          logger.log('👤 [MyQuestions] 从localStorage获取用户信息:', userInfo);
          const userId = userInfo.id || '1953810929896525824'; // 使用正确的默认ID
          return String(userId); // 确保返回字符串格式
        }
      } catch (error) {
        logger.error('❌ [MyQuestions] 解析用户信息失败:', error);
      }
      logger.warn('⚠️ [MyQuestions] 无法获取用户ID，使用正确的默认值');
      return '1953810929896525824'; // 使用正确的用户ID
    },

    // 批量删除题目
    async bulkDelete() {
      const selectedCount = this.selectedQuestions.length;
      const confirmed = confirm(`确定要删除所选的 ${selectedCount} 个题目吗？此操作不可恢复。`);
      if (!confirmed) return;

      try {
        logger.log('🗑️ [MyQuestions] 批量删除题目:', this.selectedQuestions.map(q => q.id));
        
        // 从本地存储批量删除
        const { default: localQuestionStorage } = await import('@/utils/localStorage');
        const questionIds = this.selectedQuestions.map(q => q.id);
        const deletedCount = localQuestionStorage.deleteQuestions(questionIds);
        
        logger.log(`✅ [MyQuestions] 成功删除 ${deletedCount} 个题目`);
        
        // 重新加载列表
        await this.loadQuestions();
        
      } catch (error) {
        logger.error('❌ [MyQuestions] 批量删除失败:', error);
        if (this.$message && this.$message.error) {
          this.$message.error('批量删除失败，请重试');
        } else {
          alert('批量删除失败，请重试');
        }
      }
    },

    // 批量修改状态
    async bulkChangeStatus(isPublic) {
      const selectedCount = this.selectedQuestions.length;
      const statusText = isPublic ? '公开' : '私有';
      const confirmed = confirm(`确定要将所选的 ${selectedCount} 个题目设为${statusText}吗？`);
      if (!confirmed) return;

      try {
        logger.log(`🔄 [MyQuestions] 批量设为${statusText}:`, this.selectedQuestions.map(q => q.id));
        
        // 从本地存储批量更新状态
        const { default: localQuestionStorage } = await import('@/utils/localStorage');
        for (const question of this.selectedQuestions) {
          localQuestionStorage.updateQuestion(question.id, { isPublic: isPublic });
        }
        
        logger.log(`✅ [MyQuestions] 成功将 ${selectedCount} 个题目设为${statusText}`);
        
        // 重新加载列表
        await this.loadQuestions();
        
      } catch (error) {
        logger.error('❌ [MyQuestions] 批量状态修改失败:', error);
        if (this.$message && this.$message.error) {
          this.$message.error('批量状态修改失败，请重试');
        } else {
          alert('批量状态修改失败，请重试');
        }
      }
    },

    // 清除选择
    clearSelection() {
      this.questions.forEach(question => {
        question.selected = false;
      });
      this.selectAllState = false;
    },

    // 重置搜索条件
    resetSearch() {
      this.searchForm = {
        keyword: '',
        difficulty: '',
        sortBy: ''
      };
      this.currentPage = 1;
      this.loadQuestions();
    },

    // 全选/取消全选
    toggleSelectAll() {
      this.questions.forEach(question => {
        question.selected = this.selectAllState;
      });
    },

    // 快速筛选
    quickFilter(type) {
      this.searchForm.keyword = '';
      this.searchForm.difficulty = '';
      
      switch(type) {
        case 'recent':
          this.searchForm.sortBy = 'createTime';
          break;
      }
      
      this.currentPage = 1;
      this.searchQuestions();
    },

    // 共享题目
    shareQuestion(question) {
      logger.log('📤 [MyQuestions] 开始共享题目:', question);
      this.shareTargetQuestion = question;
      this.showShareModal = true;
      this.shareForm = {
        targetUserId: '',
        loading: false,
        error: ''
      };
      
      // 自动聚焦到输入框
      this.$nextTick(() => {
        if (this.$refs.targetUserIdInput) {
          this.$refs.targetUserIdInput.focus();
        }
      });
    },

    // 关闭共享弹窗
    closeShareModal() {
      this.showShareModal = false;
      this.shareTargetQuestion = null;
      this.shareForm = {
        targetUserId: '',
        loading: false,
        error: ''
      };
    },

    // 确认共享
    async confirmShare() {
      const targetUserId = this.shareForm.targetUserId.trim();
      
      if (!targetUserId) {
        this.shareForm.error = '请输入目标用户ID';
        return;
      }

      // 验证用户ID格式（必须是数字）
      if (!/^\d+$/.test(targetUserId)) {
        this.shareForm.error = '用户ID必须是数字格式';
        return;
      }

      if (!this.shareTargetQuestion || !this.shareTargetQuestion.id) {
        this.shareForm.error = '题目信息异常，请重试';
        return;
      }

      this.shareForm.loading = true;
      this.shareForm.error = '';

      try {
        logger.log('📤 [MyQuestions] 调用共享API...');
        const shareData = {
          questionId: this.shareTargetQuestion.id,
          toUserId: targetUserId
        };
        
        logger.log('📤 [MyQuestions] 共享数据:', shareData);
        
        const response = await shareQuizToUser(shareData);
        
        logger.log('✅ [MyQuestions] 共享成功:', response);
        
        logger.log(`✅ [MyQuestions] 题目"${this.shareTargetQuestion.questionName}"已成功共享给用户 ${targetUserId}`);
        
        // 关闭弹窗
        this.closeShareModal();
        
      } catch (error) {
        logger.error('❌ [MyQuestions] 共享失败:', error);
        
        let errorMessage = '共享失败，请重试';
        if (error.response) {
          errorMessage = `共享失败 (${error.response.status}): ${error.response.data?.message || '服务器错误'}`;
        } else if (error.message) {
          errorMessage = `共享失败: ${error.message}`;
        }
        
        this.shareForm.error = errorMessage;
        
        if (this.$message && this.$message.error) {
          this.$message.error(errorMessage);
        }
        
      } finally {
        this.shareForm.loading = false;
      }
    }
  },

  async mounted() {
    logger.log('📋 [MyQuestions] 页面加载完成');
    
    // 确保搜索条件为空，显示所有用户创建的题目
    this.searchForm = {
      keyword: '',
      difficulty: '',
      type: '',
      isPublic: ''
    };
    
    await this.loadQuestions();
    
    // 添加页面可见性监听
    document.addEventListener('visibilitychange', this.handleVisibilityChange);
  },

  beforeUnmount() {
    // 清理事件监听
    document.removeEventListener('visibilitychange', this.handleVisibilityChange);
  },

  watch: {
    // 监听路由变化
    '$route'(to, from) {
      logger.log('🔄 [MyQuestions] 路由变化，从', from.path, '到', to.path);
      
      // 检查是否有refresh参数（来自删除操作）
      if (to.query.refresh && !this.loading) {
        logger.log('🔄 [MyQuestions] 检测到refresh参数，强制刷新数据');
        this.loadQuestions();
        // 清除refresh参数，避免重复刷新
        this.$router.replace({ path: to.path, query: {} });
        return;
      }
      
      // 原有的创建页面返回逻辑
      if (to.path === '/my-questions' && from.path === '/question/create') {
        logger.log('✨ [MyQuestions] 从题目创建页面返回，重新加载数据');
        // 更新空状态消息
        this.emptyStateTitle = '题目创建成功！';
        this.emptyStateMessage = '您的新题目正在加载中，如果没有显示请稍后刷新页面';
        this.loadQuestions();
      } else {
        // 恢复默认消息
        this.emptyStateTitle = '还没有创建任何题目';
        this.emptyStateMessage = '点击上方的"创建新题目"按钮开始创建您的第一个编程题目';
      }
    }
  },

  async activated() {
    // keep-alive组件激活时调用
    logger.log('🔄 [MyQuestions] 组件激活');
    // 组件激活时总是刷新数据，确保显示最新状态
    if (!this.loading) {
      logger.log('🔄 [MyQuestions] 刷新数据以确保显示最新状态');
      await this.loadQuestions();
    } else {
      logger.log('🔄 [MyQuestions] 正在加载中，跳过重新加载');
    }
  }
}
</script>

<style scoped>
.my-questions-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.page-container {
  max-width: 1400px;
  margin: 0 auto;
}

/* 页面头部 */
.page-header {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  padding: 30px;
  margin-bottom: 30px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.header-left {
  flex: 1;
}

.page-title {
  font-size: 2.5em;
  margin: 0 0 10px 0;
  color: #2c3e50;
  font-weight: 700;
  display: flex;
  align-items: center;
  gap: 15px;
}

.page-title i {
  color: #667eea;
}

.page-subtitle {
  font-size: 1.1em;
  color: #7f8c8d;
  margin: 0;
}

.local-storage-notice {
  margin-top: 8px;
  padding: 8px 12px;
  background: rgba(52, 152, 219, 0.1);
  border: 1px solid rgba(52, 152, 219, 0.2);
  border-radius: 6px;
  color: #3498db;
  font-size: 0.9em;
  display: flex;
  align-items: center;
  gap: 6px;
}



.refresh-btn {
  background: linear-gradient(135deg, #3498db, #2980b9);
  color: white;
  border: none;
  padding: 12px 16px;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(52, 152, 219, 0.3);
}

.refresh-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(52, 152, 219, 0.4);
}

.refresh-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.create-btn {
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.create-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}



/* 批量操作区域 */
.bulk-actions-section {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  padding: 20px 30px;
  margin-bottom: 30px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  border-left: 4px solid #667eea;
}

.bulk-actions-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 20px;
}

.selection-info {
  display: flex;
  align-items: center;
  gap: 10px;
  color: #2c3e50;
  font-weight: 600;
}

.selection-info i {
  color: #667eea;
  font-size: 1.2em;
}

.bulk-buttons {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.bulk-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 0.9em;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 6px;
  transition: all 0.3s ease;
}

.bulk-btn.delete {
  background: #e74c3c;
  color: white;
}

.bulk-btn.delete:hover {
  background: #c0392b;
  transform: translateY(-2px);
}

.bulk-btn.public {
  background: #2ecc71;
  color: white;
}

.bulk-btn.public:hover {
  background: #27ae60;
  transform: translateY(-2px);
}

.bulk-btn.private {
  background: #f39c12;
  color: white;
}

.bulk-btn.private:hover {
  background: #e67e22;
  transform: translateY(-2px);
}

.bulk-btn.clear {
  background: #95a5a6;
  color: white;
}

.bulk-btn.clear:hover {
  background: #7f8c8d;
  transform: translateY(-2px);
}

/* 统计信息 */
.stats-section {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.stat-card {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  padding: 25px;
  display: flex;
  align-items: center;
  gap: 20px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  transition: transform 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-3px);
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
}

.stat-icon.total { background: linear-gradient(135deg, #3498db, #2980b9); }
.stat-icon.public { background: linear-gradient(135deg, #2ecc71, #27ae60); }
.stat-icon.private { background: linear-gradient(135deg, #f39c12, #e67e22); }
.stat-icon.submissions { background: linear-gradient(135deg, #9b59b6, #8e44ad); }
.stat-icon.easy { background: linear-gradient(135deg, #f1c40f, #f39c12); }
.stat-icon.popular { background: linear-gradient(135deg, #e74c3c, #c0392b); }

.stat-info h3 {
  font-size: 2em;
  margin: 0 0 5px 0;
  color: #2c3e50;
  font-weight: 700;
}

.stat-info p {
  margin: 0;
  color: #7f8c8d;
  font-size: 0.9em;
}

/* 搜索和筛选 */
.filter-section {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  padding: 25px;
  margin-bottom: 30px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.search-row {
  display: flex;
  gap: 15px;
  align-items: center;
  flex-wrap: wrap;
}

.search-box {
  position: relative;
  flex: 1;
  min-width: 300px;
}

.search-btn, .reset-btn {
  padding: 12px 20px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s ease;
}

.search-btn {
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
}

.search-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}

.reset-btn {
  background: #95a5a6;
  color: white;
}

.reset-btn:hover {
  background: #7f8c8d;
  transform: translateY(-2px);
}

.search-box i {
  position: absolute;
  left: 15px;
  top: 50%;
  transform: translateY(-50%);
  color: #7f8c8d;
}

.search-box input {
  width: 100%;
  padding: 12px 15px 12px 45px;
  border: 2px solid #e1e8ed;
  border-radius: 8px;
  font-size: 0.95em;
  transition: border-color 0.3s ease;
}

.search-box input:focus {
  outline: none;
  border-color: #667eea;
}

.filter-controls {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

.filter-controls select {
  padding: 12px 15px;
  border: 2px solid #e1e8ed;
  border-radius: 8px;
  background: white;
  cursor: pointer;
  transition: border-color 0.3s ease;
}

.filter-controls select:focus {
  outline: none;
  border-color: #667eea;
}

/* 快速操作区域 */
.quick-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 15px;
  border-top: 1px solid #e1e8ed;
  gap: 20px;
  flex-wrap: wrap;
}

.select-all {
  display: flex;
  align-items: center;
  gap: 8px;
}

.select-all-checkbox {
  width: 16px;
  height: 16px;
  cursor: pointer;
  accent-color: #667eea;
}

.select-all label {
  cursor: pointer;
  color: #2c3e50;
  font-weight: 600;
}

.quick-filters {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

.filter-label {
  color: #7f8c8d;
  font-size: 0.9em;
  margin-right: 5px;
}

.quick-filter-btn {
  padding: 6px 12px;
  border: 2px solid #e1e8ed;
  background: white;
  border-radius: 6px;
  cursor: pointer;
  font-size: 0.85em;
  font-weight: 600;
  color: #2c3e50;
  display: flex;
  align-items: center;
  gap: 5px;
  transition: all 0.3s ease;
}

.quick-filter-btn:hover {
  border-color: #667eea;
  color: #667eea;
  transform: translateY(-1px);
}

.quick-filter-btn i {
  font-size: 0.8em;
}

/* 题目列表 */
.questions-section {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  padding: 30px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
}

.loading-state, .empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #7f8c8d;
}

.loading-state i {
  font-size: 3em;
  margin-bottom: 20px;
  color: #667eea;
}

.empty-state .empty-icon {
  font-size: 4em;
  margin-bottom: 20px;
  color: #bdc3c7;
}

.empty-state h3 {
  font-size: 1.5em;
  margin-bottom: 10px;
  color: #2c3e50;
}

.empty-create-btn {
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 600;
  margin-top: 20px;
  display: inline-flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s ease;
}

.empty-create-btn:hover {
  transform: translateY(-2px);
}

.creation-notice {
  background: #fff3cd;
  border: 1px solid #ffeaa7;
  border-radius: 8px;
  padding: 15px;
  margin: 20px 0;
  text-align: left;
}

.creation-notice p {
  margin: 0 0 10px 0;
  color: #856404;
  font-weight: 600;
}

.creation-notice ul {
  margin: 0;
  padding-left: 20px;
  color: #856404;
}

.creation-notice li {
  margin: 5px 0;
}

.empty-actions {
  display: flex;
  gap: 15px;
  justify-content: center;
  flex-wrap: wrap;
}

.empty-refresh-btn {
  background: linear-gradient(135deg, #3498db, #2980b9);
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 600;
  display: inline-flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s ease;
}

.empty-refresh-btn:hover {
  transform: translateY(-2px);
}

.questions-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 25px;
}

.question-card {
  background: white;
  border: 2px solid #e1e8ed;
  border-radius: 12px;
  padding: 25px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.question-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(102, 126, 234, 0.1), transparent);
  transition: left 0.5s;
}

.question-card:hover::before {
  left: 100%;
}

.question-card:hover {
  transform: translateY(-5px);
  border-color: #667eea;
  box-shadow: 0 8px 30px rgba(102, 126, 234, 0.2);
}

.question-card.selected {
  border-color: #667eea;
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.05), rgba(118, 75, 162, 0.05));
  box-shadow: 0 4px 20px rgba(102, 126, 234, 0.15);
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
  gap: 15px;
}

.question-select {
  flex-shrink: 0;
}

.question-checkbox {
  width: 18px;
  height: 18px;
  cursor: pointer;
  accent-color: #667eea;
}

.question-title {
  font-size: 1.2em;
  font-weight: 600;
  color: #2c3e50;
  flex: 1;
  margin-right: 15px;
}

.question-actions {
  display: flex;
  gap: 5px;
}

.action-btn {
  min-width: 60px;
  height: 32px;
  padding: 6px 10px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
  transition: all 0.3s ease;
  font-size: 12px;
  font-weight: 600;
}

.action-btn.view {
  background: #2ecc71;
  color: white;
}

.action-btn.edit {
  background: #3498db;
  color: white;
}

.action-btn.share {
  background: #9b59b6;
  color: white;
}

.action-btn.delete {
  background: #e74c3c;
  color: white;
}

.action-btn:hover {
  transform: scale(1.1);
}

.question-meta {
  display: flex;
  gap: 8px;
  margin-bottom: 15px;
  flex-wrap: wrap;
}

.difficulty-badge,
.type-badge,
.status-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.8em;
  font-weight: 600;
  color: white;
}

.difficulty-badge.easy { background: #2ecc71; }
.difficulty-badge.medium { background: #f39c12; }
.difficulty-badge.hard { background: #e74c3c; }
.difficulty-badge.expert { background: #9b59b6; }

.type-badge { background: #3498db; }

.status-badge.public { background: #2ecc71; }
.status-badge.private { background: #95a5a6; }

.question-description {
  color: #7f8c8d;
  line-height: 1.5;
  margin-bottom: 15px;
  font-size: 0.9em;
}

.question-stats {
  display: flex;
  justify-content: space-between;
  padding-top: 15px;
  border-top: 1px solid #ecf0f1;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #7f8c8d;
  font-size: 0.8em;
}

.stat-item i {
  color: #bdc3c7;
}

/* 分页 */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 15px;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #ecf0f1;
}

.page-btn {
  width: 40px;
  height: 40px;
  border: 2px solid #e1e8ed;
  background: white;
  border-radius: 8px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.page-btn:hover:not(:disabled) {
  border-color: #667eea;
  color: #667eea;
}

.page-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-info {
  color: #7f8c8d;
  font-size: 0.9em;
}

/* 共享弹窗样式 */
.share-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  backdrop-filter: blur(5px);
}

.share-modal {
  background: white;
  border-radius: 16px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  min-width: 480px;
  max-width: 90vw;
  max-height: 90vh;
  overflow: hidden;
  animation: modalFadeIn 0.3s ease;
}

@keyframes modalFadeIn {
  from {
    opacity: 0;
    transform: scale(0.9) translateY(-20px);
  }
  to {
    opacity: 1;
    transform: scale(1) translateY(0);
  }
}

.share-modal-header {
  background: linear-gradient(135deg, #9b59b6, #8e44ad);
  color: white;
  padding: 20px 25px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.share-modal-header h3 {
  margin: 0;
  font-size: 1.3em;
  font-weight: 600;
}

.close-btn {
  background: none;
  border: none;
  color: white;
  font-size: 1.2em;
  cursor: pointer;
  padding: 5px;
  border-radius: 4px;
  transition: background-color 0.3s ease;
}

.close-btn:hover {
  background: rgba(255, 255, 255, 0.2);
}

.share-modal-body {
  padding: 25px;
}

.question-info {
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #9b59b6;
}

.question-info h4 {
  margin: 0 0 8px 0;
  color: #2c3e50;
  font-size: 1.1em;
  font-weight: 600;
}

.question-info p {
  margin: 0;
  color: #7f8c8d;
  font-size: 0.9em;
}

.share-form {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.share-form label {
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 5px;
}

.share-form input {
  padding: 12px 15px;
  border: 2px solid #e1e8ed;
  border-radius: 8px;
  font-size: 1em;
  transition: border-color 0.3s ease;
}

.share-form input:focus {
  outline: none;
  border-color: #9b59b6;
}

.error-message {
  color: #e74c3c;
  font-size: 0.9em;
  padding: 8px 12px;
  background: #fdf2f2;
  border: 1px solid #fecaca;
  border-radius: 6px;
  margin-top: 5px;
}

.share-modal-footer {
  padding: 20px 25px;
  background: #f8f9fa;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  border-top: 1px solid #e1e8ed;
}

.cancel-btn,
.confirm-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s ease;
}

.cancel-btn {
  background: #95a5a6;
  color: white;
}

.cancel-btn:hover {
  background: #7f8c8d;
}

.confirm-btn {
  background: linear-gradient(135deg, #9b59b6, #8e44ad);
  color: white;
}

.confirm-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(155, 89, 182, 0.3);
}

.confirm-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

/* 调试信息样式已移除 */

/* 响应式设计 */
@media (max-width: 768px) {
  .my-questions-page {
    padding: 10px;
  }
  
  .header-content {
    flex-direction: column;
    gap: 20px;
    text-align: center;
  }
  
  .page-title {
    font-size: 2em;
  }
  
  .stats-section {
    grid-template-columns: 1fr;
  }
  
  .filter-section {
    flex-direction: column;
    align-items: stretch;
  }

  .search-row {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-box {
    min-width: auto;
  }

  .search-btn, .reset-btn {
    width: 100%;
    justify-content: center;
  }
  
  .filter-controls {
    justify-content: stretch;
    flex-direction: column;
  }
  
  .filter-controls select {
    flex: 1;
    margin-bottom: 10px;
  }

  .quick-actions {
    flex-direction: column;
    align-items: stretch;
    gap: 15px;
  }

  .quick-filters {
    justify-content: center;
    flex-wrap: wrap;
  }
  
  .questions-grid {
    grid-template-columns: 1fr;
  }
  
  .question-header {
    flex-direction: column;
    gap: 10px;
  }
  
  .question-actions {
    align-self: flex-end;
  }

  .bulk-actions-content {
    flex-direction: column;
    gap: 15px;
    text-align: center;
  }

  .bulk-buttons {
    justify-content: center;
  }

  .action-btn {
    min-width: 50px;
    height: 28px;
    padding: 4px 8px;
    font-size: 10px;
  }

  .action-btn span {
    display: none;
  }

  .action-btn i {
    font-size: 14px;
  }

  /* 共享弹窗响应式调整 */
  .share-modal {
    min-width: 90vw;
    margin: 20px;
  }

  .share-modal-header,
  .share-modal-body,
  .share-modal-footer {
    padding: 15px 20px;
  }

  .share-modal-footer {
    flex-direction: column;
  }

  .cancel-btn,
  .confirm-btn {
    width: 100%;
    justify-content: center;
  }
}
</style> 